import React, { useEffect } from "react";
import { BrowserRouter as Router } from "react-router-dom";
import { StoreProvider, useStore } from "./stores/store.jsx"; // 引入 StoreProvider
import { publicRoutes, userRoutes } from "./router/routers"; // 导入路由
import { useRoutes, useNavigate } from "react-router-dom"; // 引入 useRoutes 和 useNavigate
import Cookies from "js-cookie";
import { message } from "antd";
import { USER_TYPES } from "./utils/userUtils"; // 用户类型常量

function App() {
  return (
    <StoreProvider>
      <Router>
        <AppRoutes />
      </Router>
    </StoreProvider>
  );
}

function AppRoutes() {
  const navigate = useNavigate(); // 在 Router 内部使用 useNavigate
  const { state } = useStore(); // 获取全局状态
  const userType = state.userType; // 获取用户类型

  // 根据用户类型动态加载路由
  const routes = [
    ...publicRoutes,
    ...(userType === USER_TYPES.SUPER_ADMIN ? userRoutes.admin : []),
    ...(userType === USER_TYPES.RECRUITER ? userRoutes.recruiter : []),
    ...(userType === USER_TYPES.JOB_SEEKER ? userRoutes.jobSeeker : []),
  ];

  const routing = useRoutes(routes); // 使用 useRoutes 加载路由配置

  useEffect(() => {
    const token = Cookies.get("access_token"); // 检查是否存在 token

    const currentRoute = window.location.pathname; // 获取当前路径
    const noAuthRoutes = ["/home", "/login", "/register"]; // 不需要身份验证的路由

    if (!token && !noAuthRoutes.includes(currentRoute)) {
      // 如果没有 token 且目标路由需要身份验证，则跳转到登录页面
      message.warning("未授权，请重新登录");
      navigate("/home");
    }
  }, [navigate]);

  return routing;
}

export default App;
